/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.sourcecode.metadata.utility;

import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.service.MetadataProjectService;
import com.inspur.edp.web.common.encrypt.EncryptUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.sourcecode.metadata.entity.SourceCodeItemEntity;
import com.inspur.edp.web.sourcecode.metadata.entity.SourceCodeMetadataEntity;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import com.inspur.edp.web.common.io.FileUtility;

@Slf4j
public class SourceCodeMetadataUtility {
    /**
     * 自定义web构件 项增加文件内容作为填充
     */
    public static void sourceCodeItemsAddFileContent(SourceCodeMetadataEntity sourceCodeMetadataEntity, String projectName) {
        String strDevRootPath = getAbsoluteDevRootPath();
        strDevRootPath = getMetadataProjectPath(sourceCodeMetadataEntity.getPath());
        final String fstrDevRootPath = FileUtility.combine(strDevRootPath, "src", "app");
        if (sourceCodeMetadataEntity.getItems() != null && !sourceCodeMetadataEntity.getItems().isEmpty()) {
            sourceCodeMetadataEntity.getItems().forEach((item) ->
                    sourceCodeItemAddFileContent(item, fstrDevRootPath, projectName));
        }
    }

    /**
     * 针对文件路径 填充文件内容
     */
    private static void sourceCodeItemAddFileContent(SourceCodeItemEntity item, String strDevRootPath, String projectName) {
        String strSourcePath = replaceProjectName(item.getSourcePath(), projectName);
        String absolutePath = StringUtility.contactByRemovingRepeat(strDevRootPath, strSourcePath);
        if (FileUtility.exists(absolutePath)) {
            try {
                String strFileContent = FileUtility.readAsString(absolutePath);
                String strBase64Encoding = EncryptUtility.getInstance().Base64Encode(strFileContent);


                item.setSourceFileContent(strBase64Encoding);
            } catch (RuntimeException ex) {
                log.error("sourceCodeMetadata saving," + ex.getMessage(), ex);
            }
        } else {
            WebLogger.Instance.info("自定义web构件，文件不存在，对应路径路径:" + absolutePath);
        }
    }

    private static String replaceProjectName(String source, String projectName) {
        return source.replace("{{projectname}}", projectName);
    }

    /**
     * 获取当前元数据所在工程路径
     */
    private static String getMetadataProjectPath(String metadataFullPath) {
        String currentProjectPath = metadataFullPath;
        if (currentProjectPath.contains(MetadataUtility.getInstance().getDevRootPath())) {
            return currentProjectPath;
        } else {
            MetadataProjectService bean = SpringBeanUtils.getBean(MetadataProjectService.class);
            MetadataProject metadataProject = bean.getMetadataProjInfo(metadataFullPath);

            return java.nio.file.Paths.get(MetadataUtility.getInstance().getDevRootPath()).resolve(metadataProject.getProjectPath()).toString();
        }
    }

    /**
     * 获取开发时绝对路径
     */
    private static String getAbsoluteDevRootPath() {
        String devRootPath = MetadataUtility.getInstance().getDevRootPath();
        if (!FileUtility.isAbsolute(devRootPath)) {
            devRootPath = FileUtility.getAbsolutePathHead(devRootPath) + devRootPath;
        }
        return devRootPath;
    }
}
